package com.brush.framework.security.handler;

import cn.hutool.json.JSONUtil;
import com.brush.common.constant.Constants;
import com.brush.common.core.domain.R;
import com.brush.common.core.domain.resp.AdminUserDetails;
import com.brush.common.utils.MessageUtils;
import com.brush.common.utils.ServletUtils;
import com.brush.framework.manager.AsyncManager;
import com.brush.framework.manager.factory.AsyncTimerTaskFactory;
import com.brush.framework.web.service.AdminTokenService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 用户退出自定义实现
 */
@Component
public class AdminLogoutSuccessHandlerImpl implements LogoutSuccessHandler {

    @Autowired
    private AdminTokenService adminTokenService;

    @Override
    public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {

        //获取令牌
       AdminUserDetails  adminUserDetails = adminTokenService.getLoginUser(request);
       if (adminUserDetails != null) {
           //删除redis中的令牌
           adminTokenService.delLoginUser(adminUserDetails.getToken());
           // 记录用户退出日志
           AsyncManager.me().execute(AsyncTimerTaskFactory.recordLogininfor(adminUserDetails.getUsername(),
                   Constants.LOGOUT, MessageUtils.message("user.logout.success")));
       }

        R<Object> ok = R.ok(null, MessageUtils.message("user.logout.success"));
        ServletUtils.renderString(response, JSONUtil.toJsonStr(ok));
    }
}
